// 路由文件中，要有四个步骤
// 1、加载express
// 2、创建路由对象
// 3、把接口挂在到路由对象上
// 4、导出路由对象

const path = require('path');
const db = require(path.join(__dirname, '../utils', 'db'));
const express = require('express');
const router = express.Router();

const multer = require('multer');
const upload = multer({
    dest: 'uploads/'
});
const moment = require('moment');

// -------------------------- 写文章管理接口
// --------------- 发布新文章
router.post('/add', upload.single('cover_img'), async (req, res) => {
    // 接收客户端提交的数据(请求体)
    // console.log(req.body);
    // console.log(req.file);
    let obj = req.body;
    obj.cover_img = req.file.filename; // 上传之后的文件名
    obj.author_id = req.user.id;
    obj.pub_date = moment().format('YYYY-MM-DD HH:mm:ss');
    let r = await db('insert into article set ?', obj);
    // console.log(r); // 添加、修改、删除语句，执行结果是一个对象，里面包含了 affectedRows 属性
    if (r && r.affectedRows > 0) {
        res.send({
            status: 0,
            message: '发布文章成功'
        })
    } else {
        res.send({
            status: 0,
            message: '发布文章失败'
        })
    }
})

// --------------- 获取文章列表数据
router.get('/list', async (req, res) => {
    let pagenum = req.query.pagenum || 1;
    let pagesize = req.query.pagesize || 2;
    let cate_id = req.query.cate_id;
    let state = req.query.state;

    let w = '';
    if (cate_id) {
        w += ' cate_id=' + cate_id + ' and ';
    }
    if (state) {
        w += ` state='${state}' and `;
    }

    let r = await db(`select a.Id,a.title,a.pub_date,a.state,c.name cate_name from article a
    join category c on a.cate_id=c.Id
    where ${w} author_id =? limit ${(pagenum-1)*pagesize},${pagesize}`, req.user.id);
    let r2 = await db(`select count(*) total from article where ${w} author_id=?`, req.user.id);
    if (r) {
        res.send({
            status: 0,
            message: '获取文章列表成功',
            data: r,
            total: r2[0].total
        })
    } else {
        res.send({
            status: 1,
            message: '获取文章列表失败'
        })
    }
})

// --------------- 根据Id删除文章数据
router.get('/delete/:id', async (req, res) => {
    let id = req.params.id;
    let r = await db('delete from article where Id=?', id);
    if (r && r.affectedRows > 0) {
        res.send({
            status: 0,
            message: '删除成功'
        });
    } else {
        res.send({
            status: 1,
            message: '删除失败'
        })
    }
})

// --------------- 根据Id获取文章详情
router.get('/:id', async (req, res) => {
    let r = await db('select * from article where id = ?', req.params.id)
    if (r && r.length > 0) {
        res.send({
            status: 0,
            message: '获取文章成功',
            data: r[0]
        })
    } else {
        res.send({
            status: 1,
            message: '获取文章失败'
        })
    }
})

// --------------- 根据Id更新文章详情
router.post('/edit', upload.single('cover_img'), async (req, res) => {
    let obj = req.body; // 里面包含了 title content cate_id state
    if (req.file) {
        obj.cover_img = req.file.filename;
    }
    let r = await db('update article set ? where Id=?', [obj, req.body.Id]);
    if (r && r.affectedRows) {
        res.send({
            status: 0,
            message: '更新文章成功'
        })
    } else {
        res.send({
            status: 0,
            message: '更新文章失败'
        })
    }
})

module.exports = router;